Page({
  data: {
    dataList: [], // 订单列表数据
    isLoading: false, // 加载状态
    pageNo: 1, // 当前页码
    pageSize: 5, // 每页条数
    hasMore: true, // 是否有更多数据
    currentFilter: 'all', // 当前筛选类型
    currentStatus: '', // 当前筛选的orderStatus
    showDetailModal: false, // 控制模态框显示/隐藏
    currentOrder: null, // 当前选中的订单详情
    showActionSheet: false, // 操作弹窗显示状态
    actionButtons: [] // 动态生成的操作按钮
  },

  onLoad: function (options) {
    if (options.filter) {
      let status = '';
      switch (options.filter) {
        case 'received':
          status = '2'; // 已接单
          break;
        case 'processing':
          status = '3'; // 进行中
          break;
        case 'completed':
          status = '4'; // 已完成
          break;
      }
      this.setData({
        currentFilter: options.filter,
        currentStatus: status
      });
    }
    this.fetchOrderList();
  },

  onShow: function () {
    if (this.data.dataList.length === 0) {
      this.setData({
        pageNo: 1,
        hasMore: true
      });
      this.fetchOrderList();
    }
  },

  onPullDownRefresh: function () {
    this.setData({ pageNo: 1 });
    this.fetchOrderList(true);
  },

  onReachBottom: function () {
    if (this.data.hasMore && !this.data.isLoading) {
      this.setData({ pageNo: this.data.pageNo + 1 });
      this.fetchOrderList();
    }
  },

  handleFilter: function (e) {
    const newType = e.currentTarget.dataset.type;
    const newStatus = e.currentTarget.dataset.status;

    if (this.data.currentFilter === newType) return;

    wx.showLoading({ title: '加载中...', mask: true });
    this.setData({
      currentFilter: newType,
      currentStatus: newStatus,
      pageNo: 1,
      dataList: [],
      hasMore: true
    }, () => {
      this.fetchOrderList().then(() => wx.hideLoading()).catch(() => wx.hideLoading());
    });
  },

  // 打开订单详情
  handleOrderClick(e) {
    const order = e.currentTarget.dataset.order;
    this.setData({
      currentOrder: order,
      showDetailModal: true
    });
  },

  // 关闭详情模态框
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      currentOrder: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {},

  // 打开操作菜单
  openActionSheet(e) {
    const order = e.currentTarget.dataset.order;
    let actionButtons = [];

    // 根据订单状态生成操作按钮
    switch (order.orderStatus) {
      case 1: // 待服务
        actionButtons = [{ text: '撤回订单', action: 'withdraw' }];
        break;
      case 2: // 已接单
        actionButtons = [
          { text: '申请撤回订单', action: 'applyWithdraw' },
          { text: '开始陪护', action: 'startCare' }
        ];
        break;
      case 3: // 进行中
        actionButtons = [
          { text: '申请撤回订单', action: 'applyWithdraw' },
          { text: '确认完结', action: 'confirmComplete' }
        ];
        break;
    }

    this.setData({
      showActionSheet: true,
      currentOrder: order,
      actionButtons: actionButtons
    });
  },

  // 关闭操作菜单
  closeActionSheet() {
    this.setData({ showActionSheet: false, currentOrder: null });
  },

  // 处理操作菜单点击
  handleActionClick(e) {
    const action = e.currentTarget.dataset.action;
    const order = this.data.currentOrder;
    const userInfo = wx.getStorageSync('userInfo');

    if (!userInfo?.nurseId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }

    // 撤回订单
    if (action === 'withdraw') {
      wx.showModal({
        title: '提示',
        content: `确定要撤回订单【${order.orderNo}】吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '处理中...', mask: true });
            this.updateOrderStatus({ id: order.orderId, status: 5 });
          }
        }
      });
    }

    // 申请撤回
    if (action === 'applyWithdraw') {
      wx.showModal({
        title: '提示',
        content: `确定要申请撤回订单【${order.orderNo}】吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '提交中...', mask: true });
            this.updateOrderStatus({ id: order.orderId, status: 6 });
          }
        }
      });
    }

    // 开始陪护（核心功能：状态更新为3）
    if (action === 'startCare') {
      wx.showModal({
        title: '提示',
        content: `确定要开始订单【${order.orderNo}】的陪护服务吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '处理中...', mask: true });
            this.updateOrderStatus({ id: order.orderId, status: 3 });
          }
        }
      });
    }

    // 确认完结（状态更新为4）
    if (action === 'confirmComplete') {
      wx.showModal({
        title: '提示',
        content: `确定要完结订单【${order.orderNo}】吗？`,
        success: (res) => {
          if (res.confirm) {
            wx.showLoading({ title: '处理中...', mask: true });
            this.updateOrderStatus({ id: order.orderId, status: 4 });
          }
        }
      });
    }
  },

  // 统一更新订单状态接口
  updateOrderStatus(params) {
    wx.request({
      url: 'http://localhost:8080/orders/updataStatus',
      method: 'PUT', // 保持原有请求方法
      data: params, // 参数：id和status（3=开始陪护）
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 201) {
          wx.showToast({ title: '操作成功', icon: 'success' });
          // 刷新列表显示最新状态
          this.setData({ pageNo: 1, dataList: [] }, () => this.fetchOrderList());
        } else {
          wx.showToast({ title: res.data.msg || '操作失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      },
      complete: () => {
        wx.hideLoading();
        this.closeActionSheet();
        this.closeDetailModal();
      }
    });
  },

  // 订单列表请求（保持不变）
  fetchOrderList: function (isRefresh = false) {
    return new Promise((resolve, reject) => {
      if (this.data.isLoading) {
        resolve();
        return;
      }

      const userInfo = wx.getStorageSync('userInfo');
      if (!userInfo?.nurseId) {
        wx.showToast({ title: '请先登录', icon: 'none' });
        this.setData({ isLoading: false });
        reject('未获取到用户信息');
        return;
      }

      this.setData({ isLoading: true });
      const params = {
        nurseId: userInfo.nurseId,
        pageNo: this.data.pageNo,
        pageSize: this.data.pageSize
      };
      if (this.data.currentStatus !== '') {
        params.orderStatus = this.data.currentStatus;
      }

      wx.request({
        url: 'http://localhost:8080/orders/list',
        method: 'GET',
        data: params,
        success: (res) => {
          if (res.statusCode === 200 && res.data.code === 200 && res.data.data) {
            const outerData = res.data;
            const innerData = outerData.data;
            if (innerData && innerData.code === 200 && innerData.data) {
              const responseData = innerData.data;
              const newDataList = responseData.dataList || [];
              const totalCount = responseData.totalCount || 0;

              const currentDataList = isRefresh ? newDataList : [...this.data.dataList, ...newDataList];
              this.setData({
                dataList: currentDataList,
                hasMore: currentDataList.length < totalCount
              });
              resolve();
            } else {
              wx.showToast({ title: '暂无数据', icon: 'none' });
              reject();
            }
          } else {
            wx.showToast({ title: '获取数据失败', icon: 'none' });
            reject();
          }
        },
        fail: () => {
          wx.showToast({ title: '网络请求失败', icon: 'none' });
          reject();
        },
        complete: () => {
          this.setData({ isLoading: false });
          if (isRefresh) wx.stopPullDownRefresh();
        }
      });
    });
  },

  // 保留原有的开始陪护方法（适配模态框按钮）
  startCare() {
    const order = this.data.currentOrder;
    if (!order) return;

    wx.showModal({
      title: '提示',
      content: `确定要开始订单【${order.orderNo}】的陪护服务吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...', mask: true });
          this.updateOrderStatus({
            id: order.orderId,
            status: 3 // 目标状态：进行中
          });
        }
      }
    });
  },

  // 保留原有的确认完结方法（适配模态框按钮）
  confirmComplete() {
    const order = this.data.currentOrder;
    if (!order) return;

    wx.showModal({
      title: '提示',
      content: `确定要完结订单【${order.orderNo}】吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...', mask: true });
          this.updateOrderStatus({
            id: order.orderId,
            status: 4 // 目标状态：已完成
          });
        }
      }
    });
  }
});